import { useEffect, useRef } from 'react';
import { ctx2 } from '../../../../../module';

let pendingAdjustCamera = false;

export const updatePendingAdjustCamera = (pending: boolean) => {
  pendingAdjustCamera = pending;
};

export const useDollyCamera = () => {
  const didDollyRef = useRef(false);

  useEffect(() => {
    const deltaCameraDistance = 2.5e5;
    let rafId: number;

    const scheduleDolly = () => {
      if (pendingAdjustCamera) {
        rafId = requestAnimationFrame(scheduleDolly);
      } else {
        ctx2.viewer.sceneSetup.trackballControls.dollyCamera(
          deltaCameraDistance,
        );
        didDollyRef.current = true;
      }
    };

    scheduleDolly();

    return () => {
      cancelAnimationFrame(rafId);
      if (didDollyRef.current) {
        ctx2.viewer.sceneSetup.trackballControls.dollyCamera(
          -deltaCameraDistance,
        );
      }
    };
  }, []);
};
